package com.dnjn.happiness.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.datascope.annotation.DataScope;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.emo.api.RemoteUserRecordFerService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.domain.PositionLadder;
import com.dnjn.happiness.system.api.domain.SysTeam;
import com.dnjn.happiness.system.domain.vo.ExportTeamVO;
import com.dnjn.happiness.system.domain.vo.SysTeamVO;
import com.dnjn.happiness.system.domain.vo.TeamLineChartVO;
import com.dnjn.happiness.system.domain.vo.TeamUserSituationVO;
import com.dnjn.happiness.system.mapper.SysTeamMapper;
import com.dnjn.happiness.system.service.ISysDeptService;
import com.dnjn.happiness.system.service.ISysTeamService;
import com.dnjn.happiness.system.service.ISysUserService;
import com.dnjn.happiness.system.util.GenerateInviteCode;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 人员架构Service业务层处理
 *
 * @author amber
 * @date 2024-01-02
 */
@Service
public class SysTeamServiceImpl  extends ServiceImpl<SysTeamMapper, SysTeam>  implements ISysTeamService
{
    private static final Logger log = LoggerFactory.getLogger(SysTeamServiceImpl.class);
    @Autowired
    private ISysUserService userService;

    @Autowired
    private GenerateInviteCode generateInviteCode;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private RemoteUserRecordFerService remoteUserRecordFerService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> inviteCodeBind(SysTeamVO vo) {
        HashMap<String, Object> map = new HashMap<>();
        String mes = "";
        Long userId = SecurityUtils.getUserId();
        String inviteCode = vo.getInviteCode();
        Assert.notNull(inviteCode, "邀请码不能为空!");
        SysTeam parentTeam = baseMapper.getTeamByinviteCode(inviteCode);
        SysTeam currTeam = baseMapper.getTeamByUserId(userId);
        if (null == parentTeam) {
            //绑定的上级没有team的话
            mes = "当前邀请码无效";
        }
        //先校验是否是同一个部门下的用户
        Boolean flag = false;
        SysUser parentUser = userService.selectUserInfo(parentTeam.getUserId());
        SysUser currUser = userService.selectUserInfo(userId);
        if (null == currTeam && null != currUser) {
            //当前登陆人没有team,创建team
            currTeam = new SysTeam().setUserId(userId).setInviteCode(generateInviteCode.getInviteCode());
        }
        if (null != parentUser && null != currUser && !ObjectUtils.isEmpty(currUser.getDeptId())) {
            SysDept dept = deptService.selectDeptById(currUser.getDeptId());
            Long parentDeptId = dept.getParentId();
            if (currUser.getDeptId().equals(parentUser.getDeptId()) || parentDeptId.equals(parentUser.getDeptId())) {
                flag = true;
            }
        }

        if (!flag) {
            mes = "不同部门车间不能关联！";
        }
        if (currTeam.getInviteCode().equals(inviteCode)) {
            mes = "不能关联自己！";
        }
        //不能关联自己的下级
        //下级team列表
        List<SysTeam> sysTeamList = baseMapper.selectList(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getDeleted, "0").eq(SysTeam::getParentId, currTeam.getTeamId()));
        if (!CollectionUtils.isEmpty(sysTeamList)) {
            for (SysTeam item : sysTeamList) {
                if (item.getInviteCode().equals(inviteCode)) {
                    mes = "不能关联自己的下级！";
                }
                //给所有下级塞superId
                item.setSuperId(parentTeam.getTeamId());
                baseMapper.updateById(item);
            }
        }
        currTeam.setParentId(parentTeam.getTeamId());
        currTeam.setParentName(parentUser.getNickName());
        if (!ObjectUtils.isEmpty(parentTeam.getParentId())) {//如果上级有父级，就更新自己的祖级
            currTeam.setSuperId(parentTeam.getParentId());
        }
        currTeam.setLevel(parentTeam.getLevel() + 1);
        baseMapper.updateById(currTeam);
        //更新上级的团队人数
        parentTeam.setMemberTotal(parentTeam.getMemberTotal() + 1);
        baseMapper.updateById(parentTeam);
        map.put("mes", mes);
        map.put("team", currTeam);
        return map;
    }

    @Override
    public SysTeam getTeamByUserId(Long userId) {
        return baseMapper.getTeamByUserId(userId);
    }

    @Override
    public AjaxResult getInfoByUserId(Long userId) {
        SysTeam sysTeam = baseMapper.getTeamByUserId(userId);
        SysUser sysUser = userService.selectUserInfo(userId);
        //判断用户表是否有数据，并且team表没有，创建team记录。
        if (null != sysUser && null == sysTeam) {
            sysTeam = new SysTeam().setUserId(userId).setInviteCode(generateInviteCode.getInviteCode());
            ;
            baseMapper.insert(sysTeam);
        }
        if (null != sysTeam && !ObjectUtils.isEmpty(sysTeam.getParentId())) {
            SysTeam parentTeam = baseMapper.queryInfoByTeamId(sysTeam.getParentId());
            if (null != parentTeam) {
                sysTeam.setParentName(parentTeam.getNickName());
            }
        }
        if (StringUtils.isEmpty(sysTeam.getInviteCode())) {
            sysTeam.setInviteCode(generateInviteCode.getInviteCode());
            int i = baseMapper.updateById(sysTeam);
        }
        String codeBase64 = generateCode(sysTeam);
        return AjaxResult.success().put("sysTeam", sysTeam).put("codeBase64", codeBase64);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult unBind(SysTeamVO vo) {
        Long userId = vo.getUserId();
        Assert.notNull(userId, "解绑对象不能为空!");
        Assert.notNull(vo.getUnBindType(), "解绑类型不能为空!");
        String unBindType = vo.getUnBindType().getCode();

        //上级团队人数 - 1
        SysTeam currTeam = baseMapper.getTeamByUserId(userId);
        if (null == currTeam || ObjectUtils.isEmpty(currTeam.getParentId())) {
            return AjaxResult.error("当前组织信息有误");
        }
        SysTeam parentTeam = baseMapper.selectById(currTeam.getParentId());
        Integer memberTotal = parentTeam.getMemberTotal();
        if (memberTotal <= 1) {
            memberTotal = 0;
        } else {
            memberTotal = memberTotal - 1;
        }
        parentTeam.setMemberTotal(memberTotal);
        baseMapper.updateById(parentTeam);

        //解除上级关联关系
        int i = baseMapper.unBindParentTeamByUserId(userId);
        if ("SinglePoint".equals(unBindType)) {
            //单点解绑
            //解除superId为当前team的parentId的
            if (!ObjectUtils.isEmpty(currTeam.getParentId())) {
            }
        }
        if ("Multipoint".equals(unBindType)) {
            //多点解绑 是否需要将当前解绑人的团队人数 置0？todo
            //解除所有下级关联关系
            baseMapper.unBindChildTeamByTeamId(currTeam.getTeamId());
            //解除superId为当前teamId得
            baseMapper.unBindSuperTeamByTeamId(currTeam.getTeamId());
            currTeam.setMemberTotal(0);
            currTeam.setParentId(null);
            currTeam.setSuperId(null);
            baseMapper.updateById(currTeam);
        }

        //如果当前解绑人有父级，更新当前登陆人下的所有下一级的superId为空！
        List<SysTeam> childList = baseMapper.selectList(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getParentId, currTeam.getTeamId()).eq(SysTeam::getDeleted, "0"));
        if (!CollectionUtils.isEmpty(childList)) {
            for (SysTeam childTeam : childList) {
                baseMapper.updateSuperId(childTeam.getTeamId());
            }
        }

        return AjaxResult.success();
    }


    private Boolean checkDeptId(Long userId, Long userId1) {
        Boolean flag = false;
        SysUser sysUser = userService.selectUserInfo(userId);
        SysUser sysUser1 = userService.selectUserInfo(userId1);
        if (null != sysUser && null != sysUser1 && sysUser.getDeptId().equals(sysUser1.getDeptId())) {
            flag = true;
        }
        return flag;
    }

    @Override
    public SysTeam queryInfoByTeamId(Long teamId) {
        return baseMapper.queryInfoByTeamId(teamId);
    }

    @Override
    public AjaxResult getTeamListByUserIdAndParentId(Long userId, String nickName) {
        List<SysTeam> list = new ArrayList<>();
        SysTeam team = baseMapper.getTeamByUserId(userId);
        if (null != team) {
            Long teamId = team.getTeamId();
            list = baseMapper.getTeamListByUserIdAndParentId(teamId, nickName);
            //查人数
            if (!CollectionUtils.isEmpty(list)) {
                for (SysTeam sysTeam : list) {
                    Long count = baseMapper.selectCount(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getParentId, sysTeam.getTeamId()).eq(SysTeam::getDeleted, "0"));
                    sysTeam.setMemberTotal(count.intValue());
                    //是否评价，
                    LocalDateTime appraiseTime = sysTeam.getAppraiseTime();
                    if (Objects.isNull(appraiseTime)) {
                        sysTeam.setHasAppraise(true);
                    } else {
                        LocalDateTime now = LocalDateTime.now();
                        Duration duration = Duration.between(now, appraiseTime);
                        if (Math.abs(duration.toDays()) >= 7) {
                            sysTeam.setHasAppraise(true);
                        } else {
                            LocalDateTime plusDays = appraiseTime.plusDays(7);
                            duration = Duration.between(now, plusDays);
                            sysTeam.setHasAppraise(false);
                            sysTeam.setCountdown(Math.abs(duration.toDaysPart()) + "天" + Math.abs(duration.toHoursPart()) + "时" + Math.abs(duration.toMinutesPart()) + "分后可评价");
                        }
                    }
                    //评价倒计时

                    //当天是否打卡
                    R<Boolean> result = remoteUserRecordFerService.hasClockInToday(sysTeam.getUserId(), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
                        sysTeam.setHasClockIn(result.getData());
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }



    //生成二维码流并将其返回给前端调用者
    public String generateCode(SysTeam sysTeam) {
        String codeBase64 = null;
        try {
            //将生成的二维码文件直接返回给前端响应流
            codeBase64 = QrCodeService.getQRCodeBase64(sysTeam.getInviteCode(), 300, 300);
        } catch (Exception e) {
            return codeBase64;
        }
        return codeBase64;
    }

    @Override
    public List<PositionLadder> queryPositionListByTeamId(Long teamId) {
        return baseMapper.queryPositionListByTeamId(teamId);
    }


    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<ExportTeamVO> getPage(ExportTeamVO vo, Page page) {
        Page<ExportTeamVO> voPage = baseMapper.getPage(vo, page);
        if (!CollectionUtils.isEmpty(voPage.getRecords())) {
            voPage.getRecords().forEach(item -> {
                if (getChildCount(item.getTeamId()) > 0) {
                    item.setIsManager(true);
                } else {
                    item.setIsManager(false);
                }
            });
        }
        return voPage;
    }


    @Override
    public List<ExportTeamVO> getPageList(ExportTeamVO vo) {
        return baseMapper.getPageList(vo);
    }

    @Override
    public List<SysUser> getUsersByPositionAndTeamId(Map<String, Object> map) {
        return baseMapper.getUsersByPositionAndTeamId(map);
    }


    private Integer rowIndex;
    /**
     * 组装树形结构数据
     */
    @Override
    public List<ExportTeamVO> buildTreeList(HttpServletResponse response, String sheetName, List<ExportTeamVO> list) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        List<ExportTeamVO> returnList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return returnList;
        }
        List<Long> longList = list.stream().map(ExportTeamVO::getTeamId).collect(Collectors.toList());
        SXSSFWorkbook workbook = new SXSSFWorkbook(500);
        SXSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0, sheetName);
        this.rowIndex = 0;
        for (ExportTeamVO item : list) {
            //不包含在总的id集合,就认为是第一层的
            if (!longList.contains(item.getParentId())) {
                Integer cellIndex = 0;
                SXSSFRow row = sheet.createRow(rowIndex);
                SXSSFCell cell = row.createCell(cellIndex);
                cell.setCellValue(item.getEmpno() + item.getNickName());
                //递归查询 封装 当前对象的所有子集
                funRecursion(list, item, sheet, cellIndex);
                returnList.add(item);
                this.rowIndex++;
            }
        }
        if (returnList.isEmpty()) {
            returnList = list;
        }
        try {
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(workbook);
        }
        return returnList;
    }


    private void funRecursion(List<ExportTeamVO> list, ExportTeamVO item, SXSSFSheet sheet, Integer cellIndex) {
        cellIndex++;
        //获取所有的子集列表
        List<ExportTeamVO> childList = getChildList(list, item, cellIndex);
        item.setChild(childList);
        //继续循环判断子集是否还有下级
        for (ExportTeamVO child : childList) {

            this.rowIndex++;
            Integer cell1 = cellIndex;
            SXSSFRow row = sheet.createRow(rowIndex);
            SXSSFCell cell = row.createCell(child.getCellIndex());
            cell.setCellValue(child.getEmpno() + child.getNickName());
            if (getChildList(list, child, cellIndex).size() > 0) {
                funRecursion(list, child, sheet, cellIndex++);
            }
        }
    }

    private List<ExportTeamVO> getChildList(List<ExportTeamVO> list, ExportTeamVO item, Integer cellIndex) {
        List<ExportTeamVO> childList = new ArrayList<>();
        Iterator<ExportTeamVO> iterator = list.iterator();
        while (iterator.hasNext()) {
            ExportTeamVO tNext = iterator.next();
            if (!ObjectUtils.isEmpty(tNext.getParentId()) && item.getTeamId().longValue() == tNext.getParentId().longValue()) {
                tNext.setCellIndex(cellIndex);
                childList.add(tNext);
            }
        }
        return childList;
    }


    @Override
    public AjaxResult getTeamReportForms(String nickName, Long deptId) {
        //递归所有 查询有下级的列表
        List<SysTeam> listAll = baseMapper.selectTeamAll(nickName, deptId);
        return AjaxResult.success(getLeaderList(listAll));
    }

    @Override
    public List<SysTeam> getLeaderList(List<SysTeam> listAll) {
        List<Long> parentLongList = lambdaQuery().eq(SysTeam::getDeleted, "0").list().stream().map(SysTeam::getParentId).collect(Collectors.toList());
        List<SysTeam> leaderList = new ArrayList<>();
        for (SysTeam team : listAll) {
            //如果当前用户的teamId在所有的parentId集合中，就表示有下级
            if (parentLongList.contains(team.getTeamId())) {
                leaderList.add(team);
                // 30天
                //是否考核，
                if (Objects.isNull(team.getCheckTime())) {
                    team.setHasCheck(true);
                } else {
                    LocalDateTime checkTime = team.getCheckTime();
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(checkTime, now);
                    if (Math.abs(duration.toDays()) >= 30) {
                        team.setHasCheck(true);
                    } else {
                        team.setHasCheck(false);
                    }
                }
            }
        }

        return leaderList;
    }

    @Override
    public List<SysTeam> getManager(Long userId) {
        ArrayList<SysTeam> sysTeams = new ArrayList<>();
        SysTeam sysTeam = getTeamByUserId(userId);
        if (null != sysTeam) {
            Long parentId = sysTeam.getParentId();
            if (null != parentId) {
                SysTeam team = queryInfoByTeamId(parentId);
                if (null != team) {
                    sysTeams.add(team);
                    SysTeam superTeam = queryInfoByTeamId(team.getParentId());
                    if (null != superTeam) {
                        sysTeams.add(superTeam);
                    }
                }
            }
            return sysTeams;
        }
        return null;
    }

    @Override
    public List<SysTeam> getSubordinate(Long userId) {
        ArrayList<SysTeam> sysTeamList = new ArrayList<>();
        SysTeam teamByUserId = getTeamByUserId(userId);
        if (null != teamByUserId) {
            Long teamId = teamByUserId.getTeamId();
            if (null != teamId) {
                List<SysTeam> listAll = lambdaQuery().eq(SysTeam::getDeleted, Constants.UNDELETED).list();
                for (SysTeam sysTeam : listAll) {
                    Long parentId = sysTeam.getParentId();
                    if (null != parentId && parentId.equals(teamId)) {
                        sysTeamList.add(sysTeam);
                    }
                }

                List<SysTeam> teams = getInfoList(sysTeamList);

                return teams;
            }
        }


        return null;
    }

    @Override
    public SysTeam getMangerUpOne(Long userId) {
        SysTeam teamByUserId = getTeamByUserId(userId);
        if (null != teamByUserId) {
            Long parentId = teamByUserId.getParentId();
            if (null != parentId) {
                SysTeam sysTeam = queryInfoByTeamId(parentId);
                return sysTeam;
            }
        }
        return null;
    }


    private List<SysTeam> getInfoList(ArrayList<SysTeam> sysTeamList) {

        ArrayList<SysTeam> list = new ArrayList<>();

        for (SysTeam sysTeam : sysTeamList) {
            SysTeam team = baseMapper.getInfo(sysTeam.getUserId());
            list.add(team);
        }
        return list;
    }


    //递归查询当前团队所有子节点
    @Override
    public List<Long> recursionTeam(Long teamId) {
        return baseMapper.recursionTeam(teamId);
    }

    @Override
    public List<SysTeam> getLeaderListBydeptId(Long deptId) {
        return getLeaderList(baseMapper.getTeamListByDeptId(deptId));
    }

    @Override
    public Integer queryRequiredCommunicateCount(Integer startInterval, Integer endInterval, int criticalValue, List<Long> longList) {
        return baseMapper.queryRequiredCommunicateCount(startInterval, endInterval, criticalValue, longList);
    }

    @Override
    public Integer queryNormalCount(Integer startInterval, Integer endInterval, int criticalValue, List<Long> longList) {
        return baseMapper.queryNormalCount(startInterval, endInterval, criticalValue, longList);
    }

    @Override
    public Page<TeamUserSituationVO> getGraphicReportsPage(Page page, HashMap<String, Object> map) {
        return baseMapper.getGraphicReportsPage(page, map);
    }

    @Override
    public BigDecimal selectYesterdayScoreAvgByUserId(Long userId) {
        return baseMapper.selectYesterdayScoreAvgByUserId(userId);
    }

    @Override
    public Integer selectDaysByUserId(Long userId) {
        return baseMapper.selectDaysByUserId(userId);
    }

    @Override
    public List<TeamLineChartVO> selectDataByWeek(String weekOfYear, Long userId) {
        return baseMapper.selectDataByWeek(weekOfYear, userId);
    }

    @Override
    public List<TeamLineChartVO> getWeekList() {
        return baseMapper.getWeekList();
    }

    @Override
    public List<SysTeam> getSysTeamByUserId(List<SysTeam> dto) {
        //todo

        List<SysTeam> returnList = new ArrayList<SysTeam>();
        List<Long> tempList = dto.stream().map(SysTeam::getTeamId).collect(Collectors.toList());
        for (SysTeam team : dto) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(team.getParentId())) {
                recursionFn(dto, team);
                returnList.add(team);
            }
        }

        return null;
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<SysTeam> list, SysTeam t) {
        // 得到子节点列表
        List<SysTeam> childList = getChildListTeam(list, t);
        t.setChildren(childList);
        for (SysTeam tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysTeam> list, SysTeam t) {
        return getChildListTeam(list, t).size() > 0;
    }


    /**
     * 得到子节点列表
     */

    private List<SysTeam> getChildListTeam(List<SysTeam> list, SysTeam t) {
        List<SysTeam> tlist = new ArrayList<SysTeam>();
        Iterator<SysTeam> it = list.iterator();
        while (it.hasNext()) {
            SysTeam n = (SysTeam) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getTeamId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }


    @Override
    public List<SysTeam> getTeamList(Boolean aBoolean) {


        // 权限控制 判断当前用户s是否包含超级管理员
        List<SysTeam> list = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();
        if (aBoolean) {
            if (!Objects.isNull(SecurityUtils.getUserId())) {
                List<SysTeam> listAll = baseMapper.selectList(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getDeleted, "0"));
                List<Long> parentLongList = lambdaQuery().eq(SysTeam::getDeleted, "0").list().stream().map(SysTeam::getParentId).collect(Collectors.toList());
                for (SysTeam team : listAll) {
                    //如果当前用户的teamId在所有的parentId集合中，就表示有下级
                    if (parentLongList.contains(team.getTeamId())) {
                        list.add(team);
                    }
                }
                for (SysTeam sysTeam : list) {
                    String teamName = baseMapper.queryInfoByTeamId(sysTeam.getTeamId()).getNickName();
                    sysTeam.setTeamName(teamName);
                }
                return list;
            }
        } else {
            SysTeam currTeam = baseMapper.selectOne(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getUserId, userId).eq(SysTeam::getDeleted, "0"));
            if (null != currTeam) {
                getChildList(currTeam.getTeamId(), list);
            }
            for (SysTeam sysTeam : list) {
                String teamName = baseMapper.queryInfoByTeamId(sysTeam.getTeamId()).getNickName();
                sysTeam.setTeamName(teamName);
            }
            return list;

        }
        return list;
    }

    public void getChildList(Long teamId, List<SysTeam> list) {
        List<SysTeam> childList = baseMapper.selectList(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getParentId, teamId).eq(SysTeam::getDeleted, "0"));
        if (childList.size() > 0) {
            for (SysTeam child : childList) {
                Long count = baseMapper.selectCount(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getParentId, child.getTeamId()).eq(SysTeam::getDeleted, "0"));
                if (count != 0) {
                    list.add(child);
                }
                getChildList(child.getTeamId(), list);
            }

        }
    }

    /**
     * 查询所有普通员工
     */
    @Override
    public List<SysTeam> getEmployees(List<SysTeam> sysTeams) {

        List<SysTeam> employees = new ArrayList<>();

        List<Long> parentLongList = lambdaQuery().eq(SysTeam::getDeleted, "0").list().stream().map(SysTeam::getParentId).collect(Collectors.toList());//所有父id
        for (SysTeam sysTeam : sysTeams) {
            if (!parentLongList.contains(sysTeam.getTeamId()) && null != sysTeam.getParentId()) {

                // 30天
                //是否考核，
                if (Objects.isNull(sysTeam.getCheckTime())) {
                    sysTeam.setHasCheck(true);
                } else {
                    LocalDateTime checkTime = sysTeam.getCheckTime();
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(checkTime, now);
                    if (Math.abs(duration.toDays()) >= 30) {
                        sysTeam.setHasCheck(true);
                    } else {
                        sysTeam.setHasCheck(false);
                    }
                }
                employees.add(sysTeam);


            }
        }
        return employees;
    }

    @Override
    public SysTeam getParentInfoByUserId(Long userId) {
        return baseMapper.getParentInfoByUserId(userId);
    }


    @Override
    public List<SysTeam> getLeaderListByUserId(Long teamId) {
        if (Objects.isNull(teamId)) {
            SysTeam team = baseMapper.getTeamByUserId(SecurityUtils.getUserId());
            if (Objects.isNull(team)) {
                return new ArrayList<>();
            }
            teamId = team.getTeamId();
        }
        ArrayList<SysTeam> returnList = new ArrayList<>();
        getChildList1(teamId, returnList);
        List<SysTeam> leaderList = getLeaderList(returnList);
        return leaderList;
    }

    @Override
    public void getChildList1(Long teamId, List<SysTeam> list) {
        List<SysTeam> childList = baseMapper.selectChildList(teamId);
        if (childList.size() > 0) {
            for (SysTeam child : childList) {
                list.add(child);
                getChildList(child.getTeamId(), list);
            }

        }
    }

    @Override
    public Long getChildCount(Long teamId) {
        return baseMapper.selectCount(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getParentId, teamId).eq(SysTeam::getDeleted, Constants.UNDELETED));
    }

    @Override
    public void updateAppraiseTime(Long userId){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(now);
        baseMapper.updateAppraiseTime(userId,format);
    }

    @Override
    public Long selectCountByUserId(Long userId) {
        return baseMapper.selectCount(
                Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getDeleted, "0").eq(SysTeam::getUserId, userId));
    }
}
